package org.cycuchy.hp.components.book.kapstelki {
	
	import flash.display.DisplayObject;
	
	import mx.collections.ArrayCollection;
	
	import org.cycuchy.hp.components.KapstelekImageCanvas;
	import org.cycuchy.hp.components.book.PageWithBrowser;
	import org.cycuchy.hp.data.IDatas;
	import org.cycuchy.hp.data.KapstelekData;
	import org.cycuchy.hp.data.KapstelkiData;
	import org.cycuchy.hp.event.PreloadingImageEvent;

	public class KapstelikiPage extends PageWithBrowser {
		
		private var xCenter:uint;
		private var yCenter:uint; 
		
		public function KapstelikiPage() {
			trace("KapstelikiPage::KapstelikiPage()");
			super();
		}
		
		override public function loadContent(offset:Number):void {
			trace("KapstelikiPage::loadContent", offset);
			container.removeAllChildren();
			
			var children:Array = getChildren();
			for each (var child:DisplayObject in children) {
				if (child is KapstelekImageCanvas) {
					removeChild(child);					
				}
			}
			
			
			var data:KapstelkiData = KapstelkiData(_manager.datas);
			var cols:uint = data.cols;
			var rows:uint = data.rows;
			var imgWidth:uint = data.imgWidth;
			var imgHeight:uint = data.imgHeight;
			var imgInitialWidth:uint = data.imgInitialWidth;
			var imgInitialHeight:uint = data.imgInitialHeight;
			var verticalGap:uint = data.verticalGap;
			var horizontalGap:uint = data.horizontalGap;
			var kapstelki:ArrayCollection = data.kapstelki;
			var kapstelek:KapstelekData;
			var img:KapstelekImageCanvas;
			var count:uint = offset;
			for (var row:uint=0; row<rows; row++) {
				for (var col:uint=0; col<cols; col++) {
					if (kapstelki.length > count) {
						kapstelek = KapstelekData(kapstelki.getItemAt(count));
						img = new KapstelekImageCanvas(imgWidth/imgInitialWidth, imgHeight/imgInitialHeight, imgInitialWidth, imgInitialHeight, kapstelek.imgSrc, kapstelek.toolTipValue);
						img.x = xCenter + horizontalGap * col + col * imgInitialWidth;
						img.y = yCenter + verticalGap * row + row * imgInitialHeight;
						addChild(img);
						count++;
					}
				}
			}						
			dispatch(PreloadingImageEvent.LOAD, 0);
		}
		
		private function dispatch(event:String, index:int):void {
			var children:Array = getChildren();
			for each (var child:DisplayObject in children) {
				if (child is KapstelekImageCanvas) {
					child.dispatchEvent(new PreloadingImageEvent(event, index));					
				}
			}
		}
		
		override public function init(o:IDatas):void {
			var data:KapstelkiData = KapstelkiData(o);
			var cols:uint = data.cols;
			var rows:uint = data.rows;
			var imgInitialWidth:uint = data.imgInitialWidth;
			var imgInitialHeight:uint = data.imgInitialHeight;
			var verticalGap:uint = data.verticalGap;
			var horizontalGap:uint = data.horizontalGap;
			xCenter= width/2 - (cols*imgInitialWidth + (cols-1)*horizontalGap)/2;
			yCenter = height/2 - (rows*imgInitialHeight + (rows-1)*verticalGap)/2;
		}
		
	}
	
}